package com.logos.ruralrevitalization.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.logos.ruralrevitalization.req.AuthUserReq;
import com.logos.ruralrevitalization.service.AuthUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@Slf4j
@RequestMapping("/test")
public class TestController {

    @Resource
    private AuthUserService authUserService;

    @GetMapping("/test")
    public String test() {
        return "test";
    }

    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @PostMapping("doLogin")
    public String doLogin(@RequestBody AuthUserReq authUserReq) {
        Preconditions.checkArgument(StringUtils.isNotBlank(authUserReq.getPhone()), "手机号不能为空");
        Preconditions.checkNotNull(authUserReq.getPassword(), "密码不能为空");
        Preconditions.checkNotNull(authUserReq.getUserType(), "用户类型不能为空");
        String login = authUserService.login(authUserReq);
        if (StringUtils.isNotBlank(login)) {
            StpUtil.login(111);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            log.info("tokenInfo:{}", JSON.toJSONString(tokenInfo));
            return "登录成功";
        }
        return "登录失败";
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @GetMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }
}
